package demo.model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：jiangHaoTing
 * @date ：2025/4/15 15:36
 */
public class NoteUtils {
    /**
     * 内容获取第一张图
     */
    public static final Pattern IMG_PATTERN = Pattern.compile("(?i)<img((?!>).)+src=\"(?!data:)(\\S+)\"");
    public static final String REG_HTML = "(?i)<([a-z]+)([^<]*)\\/?>|<\\/([a-z]+)>";
    public static final String REG_A = "(<a.*>)|(<A.*>)|(</A.*>)|(</a.*>)";
    public static final String REG_TITLE = "([^\\u2E80-\\u9FFF\\w-_ \'\\(\\)（）——.]|[。、《》【】…])+";
    public static final String REG_A2 = "<a([\\w\\W]*?) href=['|\"]([\\w\\W]*?)['|\"]([\\w\\W]*?)>";
    public static final String REG_IMG = "<img([\\w\\W]*?) src\\s*?=['|\"]([\\w\\W]*?)['|\"]([\\w\\W]*?)>";
    public static final String REG_TARGET = "target=['|\"].*?['|\"']";
    public static final String REG_SRC = "src\\s*?=['|\"]?(.*?)(['|\"]|>|\\s+)";
    public static final String ERROR_MSG = "笔记文件过大无法保存，请修改后再试";
    public static final int MAX_LENGTH = 1000;
    public static final int MAX_UPLOAD_IMG = 15;
    public static final int MAX_DOWNLOAD_IMG = 100;

    /**
     * 清除所有 a 标签的链接
     * @param value
     * @return
     */
    public static String clearHref(String value) {
        if (value == null)
            return null;
        //html的标签属性肯定是以单引号或双引号包含
        Pattern p = Pattern.compile(REG_A2, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(value);
        while (m.find()) {
            String a = m.group();
            //将target属性替换为""
            String prefix = m.group(1).replaceAll(REG_TARGET, "");
            String suffix = m.group(3).replaceAll(REG_TARGET, "");
            //整段匹配不会出现错误
            String _a = "<a" + prefix + " href=\"javascript:void(0);\"" + suffix + " >";
            value = value.replace(a, _a);
        }
        return value;
    }

    public static String getFirstImgUrl(String html) {
        Matcher m = IMG_PATTERN.matcher(html);
        if (m.find()) {
            return m.group(2);
        }
        return "";
    }

}
